<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="!crud.props.searchToggle">
        <el-form size="small" label-width="70px" v-formkey="{query:toQuery}">
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="业务日期">
                <div class="flex flex-row">
                  <el-date-picker
                    v-model="query.startTime"
                    align="right"
                    unlink-panels
                    class="fl1"
                    format="yyyy - MM - dd "
                    value-format="yyyy-MM-dd"
                    default-value
                    range-separator=""
                    placeholder="开始日期"
                  />
                  <el-date-picker
                    v-model="query.endTime"
                    align="right"
                    unlink-panels
                    class="fl1"
                    format="yyyy - MM - dd "
                    value-format="yyyy-MM-dd"
                    default-value
                    range-separator=""
                    placeholder="结束日期"
                  />
                </div>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="单据编码">
                <el-input v-model="query.code"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="备注">
                <el-input v-model="query.remark"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="状态">
                <el-select
                  v-model="query.orderStatus"
                  class="filter-item"
                  clearable
                  placeholder="状态"
                  size="small"
                  style="width: 100%"
                  @change="crud.toQuery"
                >
                  <el-option
                    v-for="item in dict.common_order_status"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="供应商">
                <zSelect :value.sync="query.customerId" url="api/dropDown/basCustomerList"
                         :params="{businessAttr:'3',isContact:'1,2'}"
                         style="width:  100%"/>
              </el-form-item>
            </el-col>

            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="核销状态">
                <el-select
                  v-model="query.cancelStatus"
                  class="filter-item"
                  clearable
                  placeholder="状态"
                  size="small"
                  style="width: 100%"
                  @change="crud.toQuery"
                >
                  <el-option
                    v-for="item in dict.common_cancel_status"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="单据类型">
                <el-select v-model="query.type" style="width:  100%"  class="edit-input" placeholder="请选择单据类型" >
                  <el-option
                    v-for="(item,index) in dict.t_buy_begin_type"
                    :key="index"
                    v-if="item.seq>0"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" align="center">
              <rrOperation :crud="crud"/>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <crudOperation :permission="permission">
      </crudOperation>
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0"
                 :title="crud.status.title" width="500px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="业务日期">
            <el-date-picker
              v-model="form.busDate"
              type="date"
              disabled
              style="width: 100%;"
              default-value
              format="yyyy - MM - dd "
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="应付日期">
            <el-date-picker
              v-model="form.payDate"
              type="date"
              style="width: 100%;"
              @change="changeDate"
              default-value
              format="yyyy - MM - dd "
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="单据编码">
            <el-input v-model="form.code" disabled/>
          </el-form-item>
          <el-form-item label="供应商" prop="customerId">
            <zSelect :value.sync="form.customerId" url="api/dropDown/basCustomerList" style="width:  100%"/>
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="form.status"
              class="filter-item"
              clearable
              disabled
              placeholder="系统自动回显"
              size="small"
              style="width: 100%"
            >
              <el-option
                v-for="item in dict.common_order_status"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="金额" prop="taxAmount">
            <el-input v-model="form.taxAmount " oninput="value=value.replace(/[^\d^\.]/g,'')">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.remark"/>
          </el-form-item>
          <el-form-item label="单据类型">
            <el-select v-model="form.type" style="width:  100%" class="edit-input" placeholder="请选择单据类型">
              <el-option
                v-for="(item,index) in dict.t_buy_begin_type"
                :key="index"
                v-if="item.seq>0"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>

      <vue-context-menu :contextMenuData="contextMenuData"
                        @tableConfig="tableConfig"
                        @deletedata="deletedata"></vue-context-menu>
      <!-- 表格配置 -->
      <el-dialog title="表格配置"
                 :visible.sync="tableConfigShow"
                 width="60%">
        <j-table-column-config :columns.sync="crud.header" @tabSave="tabSave" @pit="pit"/>
      </el-dialog>

      <!--表格渲染-->
      <el-table ref="table" row-class-name="crud.tableRowClassName"
                height="700px"
                :data="crud.data"
                size="small"
                style="width: 100%;"
                v-if="isShowTable"
                @header-dragend="changeColWidth"
                @contextmenu.native="showMenu"
                :show-summary="true"
                :summary-method="crud.sumRow"
                sortable="custom"
                border
                @row-click="crud.selectRow"
                :row-style="crud.rowClass"
                :row-class-name="crud.tableRowClassName"
                @sort-change="crud.sortChange"
                @selection-change="crud.selectionChangeHandler"
                @row-dblclick="crud.dbClick">
        <el-table-column :render-header="crud.renderHeader" type="selection" width="60"/>
        <el-table-column :render-header="crud.renderHeader" type="index" prop="index" width="60" label="序号"/>
        <el-table-column
          v-if="item.visible"
          v-for="(item, index) in crud.header"
          :key="`col_${index}`"
          :prop="item.prop"
          :label="columnLabel(item)"
          :width="item.width + 'px'"
          :data-porp='item.prop'
          @contextmenu.native="showMenu"
          @header-dragend="changeColWidth"
        >
          <!-- 自定义渲染模版 -->
          <template slot-scope="scope">
            <!-- 当列key为 sort 时，渲染一个手柄icon -->
            <template v-if="item.prop =='sort'">
              <div class="handle_move">
                <i :class="scope.row['sort']"/>
              </div>
            </template>
            <template>
              <span :class="{'red':(scope.row[`type`] === 2)}" v-if="item.type == 1"
                    style="margin-left: 0px">{{ scope.row[`${item.prop}`] }}</span>
              <span v-if="item.type == 2" style="margin-left: 0px">{{ parseTime(scope.row[`${item.prop}`]) }}</span>
              <span :class="{'red':(scope.row[`type`] === 2)}" v-if="item.type == 3" style="margin-left: 0px">{{
                  getDict(`this.dict.label.${item.dictionary}["${scope.row[item.prop]}"]`)
                }}</span>
            </template>
          </template>
        </el-table-column>
        <!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('busDate')" prop="busDate" label="业务日期">-->
        <!--          <template slot-scope="scope">-->
        <!--            <span>{{ parseDate(scope.row.busDate) }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('code')" prop="code" label="单据编码" />-->
        <!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('customerCode')" prop="customerCode" label="供应商编码" />-->
        <!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('customerName')" prop="customerName" label="供应商名称" />-->
        <!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('taxAmount')" prop="taxAmount" label="金额" />-->
        <!--&lt;!&ndash;        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('noTaxAmount')" prop="noTaxAmount" label="未税金额" />&ndash;&gt;-->
        <!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('payDate')" prop="payDate" label="应付日期">-->
        <!--          <template slot-scope="scope">-->
        <!--            <span>{{ parseDate(scope.row.payDate) }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('cancelStatus')" prop="cancelStatus" label="核销状态">-->
        <!--          <template slot-scope="scope">-->
        <!--            <span>{{ dictName(dict.common_cancel_status,scope.row.cancelStatus)  }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('orderStatus')" prop="orderStatus" label="单据状态" >-->
        <!--          <template slot-scope="scope">-->
        <!--            <span>{{ dictName(dict.common_order_status,scope.row.orderStatus)  }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('remark')" prop="remark" label="备注" />-->
        <!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('createUserName')" prop="createUserName" label="添加人" />-->
        <!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('createTime')" prop="createTime" label="添加时间">-->
        <!--          <template slot-scope="scope">-->
        <!--            <span>{{ parseTime(scope.row.createTime) }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('updateUserName')" prop="updateUserName" label="修改人" />-->
        <!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('updateTime')" prop="updateTime" label="修改时间">-->
        <!--          <template slot-scope="scope">-->
        <!--            <span>{{ parseTime(scope.row.updateTime) }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('auditUserName')" prop="auditUserName" label="审核人" />-->
        <!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('auditTime')" prop="auditTime" label="审核时间">-->
        <!--          <template slot-scope="scope">-->
        <!--            <span>{{ parseTime(scope.row.auditTime) }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('closeUserName')" prop="closeUserName" label="关闭人" />-->
        <!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('closeTime')" prop="closeTime" label="关闭时间">-->
        <!--          <template slot-scope="scope">-->
        <!--            <span>{{ parseTime(scope.row.closeTime) }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column :render-header="crud.renderHeader" v-permission="['admin','buyBegin:edit','buyBegin:del']" label="操作" width="150px" align="center">-->
        <!--          <template slot-scope="scope">-->
        <!--            <udOperation-->
        <!--              :data="scope.row"-->
        <!--              :permission="permission"-->
        <!--            />-->
        <!--          </template>-->
        <!--        </el-table-column>-->
      </el-table>
      <!--分页组件-->
      <pagination/>
    </div>
  </div>
</template>

<script>
import crudBuyBegin from '@/api/erp/buyBegin'
import CRUD, {presenter, header, form, crud} from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import {getNowTime} from '@/utils'

import {publicListKey} from "@/utils/key";
import {getHeaderProperties} from "@/api/erp/headerProperties";
import {tablemixins} from "@/mixins/tablemixins";
import jTableColumnConfig from "@/components/jTableColumnConfig/jTableColumnConfig";
// crud交由presenter持有
const defaultCrud = CRUD({
  title: '采购期初', name: 'buyBegin', url: 'api/buyBegin', sort: 'id,desc', optShow: {
    add: true,
    edit: true,
    del: true,
    download: true,
    leadingIn: true,
    enable: false,
    disable: false,
    pass: true,
    reject: true
  }, query: {
    startTime: null, endDate: null, dataExtent: null,
  },
  //如果携带参数过来则禁止默认查询事件
  queryOnPresenterCreated:!window.location.href.includes('?id'),
  crudMethod: {...crudBuyBegin}
})
const defaultForm = {
  id: null,
  code: null,
  status: null,
  name: null,
  type: null,
  busDate: null,
  payDate: null,
  sourceType: null,
  sourceId: null,
  sourceCode: null,
  serialNumber: null,
  customerOrderCode: null,
  customerId: null,
  customerCode: null,
  customerName: null,
  isContact: null,
  customerAreaId: null,
  customerAreaCode: null,
  customerAreaName: null,
  customerTypeId: null,
  customerTypeCode: null,
  customerTypeName: null,
  deptId: null,
  deptCode: null,
  deptName: null,
  userId: null,
  userCode: null,
  userName: null,
  taxAmount: null,
  noTaxAmount: null,
  tax: null,
  cancelAmount: null,
  unCancelAmount: null,
  seq: null,
  orderStatus: null,
  cancelStatus: null,
  remark: null,
  orderRemark: null,
  createUserId: null,
  createUserCode: null,
  createUserName: null,
  createTime: null,
  updateUserId: null,
  updateUserCode: null,
  updateUserName: null,
  updateTime: null,
  auditUserId: null,
  auditUserCode: null,
  auditUserName: null,
  auditTime: null,
  closeUserId: null,
  closeUserCode: null,
  closeUserName: null,
  closeTime: null
}
export default {
  name: 'BuyBegin',
  components: {pagination, crudOperation, rrOperation, udOperation, jTableColumnConfig},
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud(), publicListKey, tablemixins],
  dicts: ['common_order_status', 'common_cancel_status', 't_buy_begin_type'],
  data() {
    return {
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      permission: {
        add: ['admin', 'buyBegin:add'],
        edit: ['admin', 'buyBegin:edit'],
        del: ['admin', 'buyBegin:del'],
        import: ['admin', 'buyBegin:import'],
        export: ['admin', 'buyBegin:export'],
        copy: ['admin', 'buyBegin:copy'],
        upload: ['admin', 'buyBegin:upload'],
        download: ['admin', 'buyBegin:download'],
        pass: ['admin', 'buyBegin:pass'],
        reject: ['admin', 'buyBegin:reject'],
        closed: ['admin', 'buyBegin:closed'],
        invalid: ['admin', 'buyBegin:invalid'],
        stop: ['admin', 'buyBegin:stop'],
        recover: ['admin', 'buyBegin:recover'],
      },
      rules: {
        taxAmount: [
          {required: true, message: '金额不能为空', trigger: 'blur'}
        ],
        userId: [
          {required: true, message: '客户不能为空', trigger: 'blur'}
        ],
        status: [
          {required: true, message: '状态不能为空', trigger: 'blur'}
        ],
        customerId: [
          {required: true, message: '供应商不能为空', trigger: 'blur'}
        ],
        payDate: [
          {required: true, message: '应付日期不能为空', trigger: 'blur'}
        ],
        code: [
          {required: true, message: '编码不能为空', trigger: 'blur'}
        ],
      },
      red: ['taxAmount', 'cancelAmount', 'unCancelAmount']
    }
  },
  activated() {
    if(this.$route.query.id){
      this.query.id=this.$route.query.id
      this.crud.refresh()
    }else {
      this.$route.query.id = null
    }
  },
  watch: {
    'crud.data': {
      handler(n, o) {
        if (!this.crud.data[0].isUpdate) {
          this.crud.data[0].isUpdate = true
          const dataList = this.crud.data.filter(item => item.type === 2)
          for (let i of this.red) {
            for (let data of dataList) {
              if (data[i])
                data[i] = Number(data[i]) * -1
            }
          }
        }

      },
      deep: true
    },
  },
  updated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  methods: {
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      return true
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      if (this.form.busDate == null) {
        this.form.busDate = this.getNowTime()
      }
    },
    changeDate(e) {
      this.form.busDate = e
    },
    getValue(e) {
      this.query.startTime = this.query.dataExtent[0]
      this.query.endTime = this.query.dataExtent[1]
    },
  }
}
</script>

<style scoped>
.red {
  color: red;
}

.table-img {
  display: inline-block;
  text-align: center;
  background: #ccc;
  color: #fff;
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  width: 32px;
  height: 32px;
  line-height: 32px;
}
</style>
